Function Overloading in C++
Posted on December 14, 2023 by Vishesh Namdev
Python
C
C++
Java
Function overloading in C++ allows you to define multiple functions with the same name but with different parameter lists. The compiler distinguishes between these functions based on the number, types, or order of the parameters. This feature provides flexibility and readability to your code, enabling you to use the same function name for related operations.
// Include necessary header
#include <iostream>
// Function overloading with different parameter types
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
// Function overloading with a different number of parameters
int add(int a, int b, int c) {
return a + b + c;
}
// Main function
int main() {
// Calling the overloaded functions
int sum1 = add(3, 4);
double sum2 = add(2.5, 3.5);
int sum3 = add(1, 2, 3);
// Displaying the results
std::cout << "Sum 1: " << sum1 << "\n";
std::cout << "Sum 2: " << sum2 << "\n";
std::cout << "Sum 3: " << sum3 << "\n";
return 0;
}
#include <iostream>
// Function overloading with different parameter types
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
// Function overloading with a different number of parameters
int add(int a, int b, int c) {
return a + b + c;
}
// Main function
int main() {
// Calling the overloaded functions
int sum1 = add(3, 4);
double sum2 = add(2.5, 3.5);
int sum3 = add(1, 2, 3);
// Displaying the results
std::cout << "Sum 1: " << sum1 << "\n";
std::cout << "Sum 2: " << sum2 << "\n";
std::cout << "Sum 3: " << sum3 << "\n";
return 0;
}
In this example, the add function is overloaded three times:
With different parameter types: One version takes two integers, and another takes two doubles.
With a different number of parameters: One version takes three integers.
1. Same Function Name:
(a.) Functions must have the same name.(b.) Overloading is based on the function name.
int add(int a, int b);
double add(double a, double b);
int add(int a, int b, int c);
double add(double a, double b);
int add(int a, int b, int c);
2. Different Parameter Lists:
(a.) Overloaded functions should have different parameter types, a different number of parameters, or both.
int add(int a, int b);
double add(double a, double b);
int add(int a, int b, int c);
double add(double a, double b);
int add(int a, int b, int c);
Benefits of Function Overloading:
a. Readability: Use the same function name for logically related operations, making the code more readable.b. Consistency: Provide a consistent interface for users of your code.
c. Default Arguments Alternative: Overloading is an alternative to using default arguments for flexibility.
Function overloading is a powerful feature in C++ that enhances code organization and clarity by allowing you to use familiar names for related operations.